// pages/movies/more-movie/more-movie.js
var utils = require('../../../utils/util.js');
var app = getApp();
Page({
  data: {
    movies:{},
    navigateTitle:"",
    requestUrl:"",
    totalNum :0,
    isEmpty:true,
  },
  onLoad: function (options) {
    var category = options.category;
    this.data.navigateTitle = category;
    var dataUrl = "";
    switch (category) {
      case "正在热映":
        dataUrl = app.globalData.doubanBase +"/v2/movie/in_theaters"
        break;
      case "即将上映":
        dataUrl = app.globalData.doubanBase +"/v2/movie/coming_soon"
        break;
      case "豆瓣TOP250":
        dataUrl = app.globalData.doubanBase + "/v2/movie/top250";
        break;
    }
    //定义requestUrl,指的是每一个类型的url
    this.data.requestUrl = dataUrl;
    utils.http(dataUrl, this.processDoubanData);
  },
  onMovieTap: function (event) {
    var movieId = event.currentTarget.dataset.movieid;
    console.log()
    wx.navigateTo({
      url: '../movie-detail/movie-detail?id=' + movieId,
    })
  },
  onReachBottom:function(event){
    var nextUrl = this.data.requestUrl + "?start=" + this.data.totalNum + "&count=20";
    utils.http(nextUrl, this.processDoubanData);
    wx.showNavigationBarLoading();
  },
  onPullDownRefresh:function(event){
    var refreshUrl = this.data.requestUrl +"?start=0&count=20";
    this.data.movies = {};
    this.data.isEmpty = true;
    this.data.newTotal = 0;
    utils.http(refreshUrl,this.processDoubanData);
    wx.showNavigationBarLoading();
  },
  processDoubanData: function (moviesDouban) {
    var movies = [];
    for (var idx in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[idx];
      var title = subject.title;
      if (title.length >= 6) {
        title = title.substring(0, 6) + "...";
        //截取前六位剩下的字用省略号代替
      }
      var temp = {
        moviestars: utils.convertToStarsArray(subject.rating.stars),
        title: title,
        movieaverage: subject.rating.average,
        moviecoverageUrl: subject.images.large,
        movieId: subject.id
      }
      movies.push(temp);
    }
    var newTotal = [];
    if (!this.data.isEmpty) {
      newTotal = this.data.movies.concat(movies);  
      console.log(newTotal.length)
    }else{
      newTotal = movies;
      this.data.isEmpty = false;
    }
    this.setData({
      movies: newTotal
    })
    this.data.totalNum += 20;
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },
  onReady:function(event){
      wx.setNavigationBarTitle({
        title: this.data.navigateTitle
      })
  }
})